<template>
  <div class="bom-create-page">
    <div class="page-title">{{ isEdit ? '编辑BOM' : '新建BOM' }}</div>

    <el-card shadow="never" class="section-card">
      <template #header>
        <span>基础信息</span>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="base-form" status-icon>
        <el-row :gutter="16">
          <el-col :sm="24" :md="12">
            <el-form-item label="BOM编号" prop="code">
              <el-input v-model="form.code" placeholder="自动生成或手输" :disabled="form.autoCode" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12" class="align-middle">
            <el-checkbox v-model="form.autoCode">系统编号</el-checkbox>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="BOM主题" prop="subject">
              <el-input v-model="form.subject" placeholder="请输入BOM主题" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本" />
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="默认BOM" prop="isDefault">
              <!-- 勾选为“是”，不勾选为“否” -->
              <el-checkbox v-model="form.isDefault" true-label="是" false-label="否" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="成品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入成品名称" />
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="成品编码" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请输入成品编码" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="规格型号" prop="specModel">
              <el-input v-model="form.specModel" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="成品类型" prop="productType">
              <el-select v-model="form.productType" placeholder="请选择">
                <el-option label="成品" value="FG" />
                <el-option label="半成品" value="SFG" />
                <el-option label="其他" value="OTH" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="日产量" prop="dailyOutput">
              <el-input-number v-model="form.dailyOutput" :min="0" :step="0.01" :precision="2" style="width: 100%;" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="card-header">
          <span>BOM配件</span>
          <div class="actions">
            <el-button type="primary" @click="addPart">添加</el-button>
            <el-button type="danger" :disabled="!selectedPartIds.length" @click="removeSelectedParts">移除</el-button>
          </div>
        </div>
      </template>

      <el-table :data="parts" border stripe style="width: 100%" @selection-change="onPartSel">
        <el-table-column type="selection" width="48" />
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column prop="code" label="物品编号" min-width="120" />
        <el-table-column prop="name" label="物品名称" min-width="140" />
        <el-table-column prop="spec" label="规格型号" min-width="160" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="brand" label="品牌" min-width="120" />
        <el-table-column prop="qty" label="配件数量" width="150">
          <template #header>
            <span><span class="req">*</span> 配件数量</span>
          </template>
          <template #default="{ row }">
            <el-input-number v-model="row.qty" :min="0" :precision="2" :step="1" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="lossRate" label="损耗率" width="140">
          <template #default="{ row }">
            <el-input-number v-model="row.lossRate" :min="0" :max="100" :step="1" size="small" />
            <span style="margin-left: 4px;">%</span>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty">暂无数据</div>
        </template>
      </el-table>
      <!-- 选择物品弹窗 -->
      <SelectItemDialog v-model="showSelectItem" @confirm="onSelectItems" />
    </el-card>

    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="card-header">
          <span>工艺流程</span>
          <div class="actions">
            <el-button type="primary" @click="addProcess">添加</el-button>
            <el-button type="danger" :disabled="!selectedProcessIds.length" @click="removeSelectedProcesses">移除</el-button>
          </div>
        </div>
      </template>

      <el-table :data="processes" border stripe style="width: 100%" @selection-change="onProcessSel">
        <el-table-column type="selection" width="48" />
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column prop="code" label="工序编码" width="140" />
        <el-table-column prop="name" label="工序名称" min-width="160" />
        <el-table-column prop="order" label="加工顺序" width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.order" :min="1" :max="9999" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="route" label="工艺路径" min-width="160">
          <template #default="{ row }">
            <el-input v-model="row.route" size="small" placeholder="请输入工艺路径" />
          </template>
        </el-table-column>
        <el-table-column prop="owner" label="负责人" width="120">
          <template #default="{ row }"><el-input v-model="row.owner" size="small" /></template>
        </el-table-column>
        <el-table-column prop="dept" label="部门" width="120">
          <template #default="{ row }"><el-input v-model="row.dept" size="small" /></template>
        </el-table-column>
        <el-table-column prop="uwh" label="单位工时量" width="140">
          <template #default="{ row }">
            <el-input-number v-model="row.uwh" :min="0" :step="0.5" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160">
          <template #default="{ row }"><el-input v-model="row.remark" size="small" /></template>
        </el-table-column>
        <template #empty>
          <div class="empty">暂无数据</div>
        </template>
      </el-table>
      <!-- 添加工艺路线弹窗 -->
      <SelectProcessDialog v-model="showSelectProcess" @confirm="onSelectProcesses" />
    </el-card>

    <el-card shadow="never" class="section-card">
      <template #header><span>附件</span></template>
      <div class="attachments">
        <!-- 文件卡片列表 -->
        <div v-for="(f, idx) in attachments" :key="idx" class="file-card">
          <div class="file-name">{{ f.name }}</div>
          <div class="file-meta">文件大小：{{ fmtSize(f.size) }}</div>
          <div class="file-meta">上传时间：{{ f.uploadTime }}</div>
          <div class="file-actions">
            <el-button link type="primary" @click="onReupload(idx)">重新上传</el-button>
            <el-button link type="danger" @click="onRemoveFile(idx)">删除</el-button>
          </div>
        </div>

        <!-- 上传框 -->
        <el-upload
          class="upload-block"
          drag
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          multiple
          @change="onUploadChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">点击上传 / 拖拽到此区域</div>
        </el-upload>

        <!-- 重新上传隐藏 input -->
        <input ref="reuploadInput" type="file" style="display:none" @change="onReuploadFileChange" />
      </div>
    </el-card>

    <div class="footer-bar">
      <el-button @click="goBack">关闭</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import SelectItemDialog from '../components/SelectItemDialog.vue'
import SelectProcessDialog from '../components/SelectProcessDialog.vue'
import ERP from '@/utils/Interceptors'

const router = useRouter()
const route = useRoute()
const isEdit = ref(false)
const editingId = ref<string>('')

const formRef = ref()
const form = reactive({
  code: '',
  autoCode: true,
  subject: '',
  version: '',
  // 默认BOM：勾选=“是”，不勾选=“否”
  isDefault: '否',
  productName: '',
  productCode: '',
  specModel: '',
  unit: '',
  productType: '',
  dailyOutput: undefined as number | undefined,
  remark: '',
})

const rules = {
  subject: [{ required: true, message: '请输入BOM主题', trigger: 'blur' }],
  // productName: [{ required: true, message: '请输入成品名称', trigger: 'blur' }],
}

// 生成系统编号：BOM + yyyyMMddHHmmss + 3位随机
function genBomCode() {
  const d = new Date()
  const pad = (n: number, l = 2) => n.toString().padStart(l, '0')
  const ts = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
  const rnd = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `BOM${ts}${rnd}`
}

// 勾选“系统编号”时自动生成
watch(
  () => form.autoCode,
  (on) => {
    if (on) {
      form.code = genBomCode()
    } else {
      // 仅在新建时清空，编辑模式不应清空后端回填的编号
      if (!isEdit.value) form.code = ''
    }
  },
  { immediate: false }
)

// 进入页面若默认勾选也生成一次
onMounted(() => {
  const id = (route.query.id as string) || ''
  if (id) {
    isEdit.value = true
    editingId.value = id
    loadDetails(id)
  } else {
    if (form.autoCode && !form.code) {
      form.code = genBomCode()
    }
  }
})

// BOM配件
const parts = ref<Array<any>>([])
const selectedPartIds = ref<string[]>([])
const showSelectItem = ref(false)
function addPart() { showSelectItem.value = true }
function editPart(_row: any) { ElMessage.info('编辑配件（示例）') }
function removePart(row: any) { parts.value = parts.value.filter((x) => x !== row) }
function onPartSel(rows: any[]) { selectedPartIds.value = rows.map((x: any) => x.code) }
function removeSelectedParts() {
  if (!selectedPartIds.value.length) return
  parts.value = parts.value.filter((x: any) => !selectedPartIds.value.includes(x.code))
}
function onSelectItems(rows: any[]) {
  // 将选择的物品映射为配件行，若已存在相同 code 则跳过或合并（此处跳过）
  const existCodes = new Set(parts.value.map((x:any) => x.code))
  const mapped = rows
    .filter((r:any) => !existCodes.has(r.code))
    .map((r:any) => ({
      code: r.code,
      name: r.name,
      spec: r.spec,
      unit: r.unit,
      brand: r.brand || '',
      // 新增：从物品选择带入库存与价格
      totalStock: r.totalStock ?? null,
      purchasePrice: r.purchasePrice ?? null,
      salesPrice: r.salePrice ?? null,
      stockDetails: r.stockDetails || [],
      qty: 1,
      lossRate: 0,
    }))
  parts.value = parts.value.concat(mapped)
}

// 工艺流程
const processes = ref<Array<any>>([])
const selectedProcessIds = ref<number[]>([])
const showSelectProcess = ref(false)
function addProcess() { showSelectProcess.value = true }
function editProcess(_row: any) { ElMessage.info('编辑工艺（示例）') }
function removeProcess(row: any) { processes.value = processes.value.filter((x) => x !== row) }
function onProcessSel(rows: any[]) { selectedProcessIds.value = rows.map((x: any) => x.id) }
function removeSelectedProcesses() {
  if (!selectedProcessIds.value.length) return
  processes.value = processes.value.filter((x: any) => !selectedProcessIds.value.includes(x.id))
}
function onSelectProcesses(rows: any[]) {
  // 将选中的流程映射为：工序编码、工序名称、加工顺序、工艺路径、负责人、部门、单位工时量、备注
  const start = processes.value.length
  const mapped = rows.map((r: any, idx: number) => ({
    id: r.id,
    code: r.flowNo,
    name: r.name,
    order: start + idx + 1,
    route: r.name,
    owner: '',
    dept: '',
    uwh: 0,
    remark: '',
  }))
  processes.value = processes.value.concat(mapped)
}

// 附件
const attachments = ref<Array<{ name: string; size: number; uploadTime: string; raw?: File }>>([])
const reuploadInput = ref<HTMLInputElement | null>(null)
const reuploadIndex = ref<number | null>(null)

function onUploadChange(uploadFile: any) {
  const file = uploadFile?.raw as File
  if (!file) return
  attachments.value.push({ name: file.name, size: file.size, uploadTime: new Date().toLocaleString(), raw: file })
}

function onRemoveFile(idx: number) { attachments.value.splice(idx, 1) }

function onReupload(idx: number) {
  reuploadIndex.value = idx
  reuploadInput.value?.click()
}

function onReuploadFileChange(e: Event) {
  const input = e.target as HTMLInputElement
  const file = input.files && input.files[0]
  if (file != null && reuploadIndex.value != null) {
    attachments.value[reuploadIndex.value] = { name: file.name, size: file.size, uploadTime: new Date().toLocaleString(), raw: file }
  }
  if (input) input.value = ''
  reuploadIndex.value = null
}

function fmtSize(bytes: number) {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  const val = (bytes / Math.pow(k, i)).toFixed(2)
  return `${val} ${sizes[i]}`
}

function goBack() { router.back() }

function onSubmit() {
  // 简单校验演示
  (formRef.value as any).validate(async (ok: boolean) => {
    if (!ok) return
    const operator = localStorage.getItem('erp_userName') || localStorage.getItem('erp_realName') || 'web'
    const payload = {
      BomCode: form.autoCode ? null : (form.code || null),
      SystemCode: form.autoCode ? (form.code || null) : null,
      ProductType: form.productType || null,
      ProductCode: form.productCode || null,
      ProductName: form.productName || form.subject || null,
      SpecModel: form.specModel || null,
      Unit: form.unit || null,
      VersionTag: form.version || null,
      DrawingNo: null,
      IsDefault: form.isDefault === '是',
      DailyOutput: form.dailyOutput ?? null,
      EffectiveDate: null,
      ExpireDate: null,
      Remark: form.remark || null,
      Accessories: parts.value.map((p: any, idx: number) => ({
        ItemCode: p.code,
        ItemName: p.name,
        SpecModel: p.spec,
        Unit: p.unit,
        ItemType: null,
        Category: null,
        Brand: p.brand,
        // 写入库存与单价，供详情和成本计算
        TotalStock: p.totalStock ?? null,
        PurchasePrice: p.purchasePrice ?? null,
        SalesPrice: p.salesPrice ?? null,
        Qty: p.qty,
        SortNo: idx + 1,
        Remark: (p.lossRate || p.lossRate === 0) ? `损耗率:${p.lossRate}%` : null,
      })),
      // 后端优先使用 ProcessRoutes；RouteIds 作为兼容
      RouteIds: processes.value.map((x: any) => x.id).filter((v: any) => !!v),
      ProcessRoutes: processes.value.map((p:any, idx:number) => ({
        RouteId: p.id,
        RouteCode: p.code,
        RouteName: p.name,
        Sort: p.order ?? (idx + 1),
        Owner: p.owner || null,
        Department: p.dept || null,
        UnitWorkHours: (p.uwh != null ? Number(p.uwh) : null),
        Remark: p.remark || null,
      })),
      Attachments: attachments.value.map((f: any) => ({
        FileName: f.name,
        OriginalFileName: f.name,
        FileSize: f.size,
        ContentType: null,
        Url: null,
        Remark: null,
      })),
      Operator: operator
    }
    try {
      if (isEdit.value) {
        await ERP.put(`/api/Boms/${editingId.value}`, payload)
      } else {
        await ERP.post('/api/Boms', payload)
      }
      ElMessage.success('保存成功')
      router.push({ name: 'BOMList' })
    } catch (e:any) {
      ElMessage.error(e?.message || '保存失败')
    }
  })
}

// 加载详情用于编辑
async function loadDetails(id: string) {
  try {
    const { data } = await ERP.get(`/api/Boms/${id}`)
    const d = data?.data || {}
    // 基础信息
    // 先关闭自动编号，再回填编号，避免被 watcher 清空
    form.autoCode = false
    // BOM编号：优先接口的 code；若后端后续补充了 bomCode/systemCode 字段也兜底
    form.code = d.code || d.bomCode || d.systemCode || d.BomCode || d.SystemCode || ''
    form.subject = d.subject || ''
    form.version = d.version || ''
    form.isDefault = d.isDefault ? '是' : '否'
    form.productName = d.productName || ''
    form.productCode = d.productCode || ''
    // 规格型号/单位增加常见别名兜底
    form.specModel = d.specModel || d.model || d.Model || ''
    form.unit = d.unit || d.unitName || d.Unit || d.UnitName || ''
    form.productType = d.productType || ''
    // 日产量：规整为最多2位小数
    form.dailyOutput = (d.dailyOutput != null) ? Number(Number(d.dailyOutput).toFixed(2)) : undefined
    form.remark = d.remark || ''

    // 配件
    const acc = Array.isArray(d.accessories) ? d.accessories : []
    parts.value = acc.map((a:any) => ({
      code: a.itemCode,
      name: a.itemName,
      spec: a.specModel,
      unit: a.unit,
      brand: a.brand,
      qty: a.qty,
      lossRate: a.lossRate ?? 0,
      totalStock: a.currentStock ?? null,
      purchasePrice: null,
      salesPrice: null,
    }))

    // 工艺（仅保留 id）
    const routes = Array.isArray(d.processRoutes) ? d.processRoutes : []
    processes.value = routes.map((r:any, idx:number) => ({
      id: r.routeId, // 后端已回传 RouteId
      code: r.routeCode,
      name: r.routeName,
      order: (r.sort ?? idx + 1),
      route: r.routeName,
      owner: r.owner || '',
      dept: r.department || '',
      uwh: (r.unitWorkHours != null ? Number(r.unitWorkHours) : 0),
      remark: r.remark || '',
    }))
  } catch (e:any) {
    ElMessage.error(e?.message || '加载详情失败')
  }
}
</script>

<style scoped>
.bom-create-page { padding: 12px; }
.page-title { font-size: 18px; font-weight: 600; margin-bottom: 12px; }
.section-card { margin-bottom: 12px; }
.card-header { display: flex; align-items: center; justify-content: space-between; }
.align-middle { display: flex; align-items: center; padding-top: 2px; }
.base-form :deep(.el-form-item) { margin-bottom: 12px; }
.empty { padding: 24px; color: #999; text-align: center; }
.attachments { display: flex; gap: 12px; }
.upload-block { width: 320px; }
.footer-bar { text-align: center; margin-top: 12px; }
.req { color: #f56c6c; margin-right: 4px; }
.file-card { width: 320px; border: 1px dashed var(--el-border-color); padding: 12px; border-radius: 4px; }
.file-name { font-weight: 600; margin-bottom: 6px; }
.file-meta { color: #666; font-size: 12px; line-height: 18px; }
.file-actions { margin-top: 8px; }
</style>
